package com.card.hwatt.controllers;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.hwatt.assembler.CardAssembler;
import com.card.hwatt.assembler.CardRecordAssembler;
import com.card.hwatt.assembler.DepartmentAssembler;
import com.card.hwatt.assembler.EmployeeAssembler;
import com.card.hwatt.assembler.ScheduleAssembler;
import com.card.hwatt.dto.*;
import com.card.hwatt.service.CardService;
import com.card.hwatt.service.DepartmentService;
import com.card.hwatt.service.EmployeeService;
import com.card.hwatt.service.ScheduleService;

/**
 * 刷脸统计
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/cardrecord")
public class CardRecordController extends BaseController {

	@Autowired
	@Qualifier("employeeService")
	private EmployeeService employeeService;

	@Autowired
	@Qualifier("cardService")
	private CardService cardService;

	@Autowired
	@Qualifier("scheduleService")
	private ScheduleService scheduleService;

	@RequestMapping("/index")
	public String index() {
		return "cardrecord";
	}

	@Autowired
	@Qualifier("departmentService")
	private DepartmentService departmentService;

	@RequestMapping("/print")
	public @ResponseBody
	void print(HttpServletRequest request, HttpServletResponse response,
			Long id, String name, String startDate, String endDate) {
		if (id == null || id.intValue() == 2 || StringUtils.isEmpty(startDate)
				|| StringUtils.isEmpty(endDate)) {
			return;
		}

		Department department = DepartmentAssembler.convert(departmentService
				.get(id));
		if (department == null) {
			return;
		}

		Schedule schedule = ScheduleAssembler.convert(scheduleService.get(
				startDate, id));
		if (schedule == null) {
			return;
		}

		List<Card> cardList = loadCard(id, name, startDate, endDate, schedule);

		List<Employee> employeeList = loadEmployee(id, name);

		List<CardRecord> list = CardRecordAssembler.convert(employeeList,
				cardList, schedule, endDate);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("start", startDate);
		params.put("end", endDate);

		String title = StringUtils.EMPTY;
		try {
			Calendar calendar = Calendar.getInstance();
			String[] parsePatterns = { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d" };
			calendar.setTime(DateUtils.parseDate(startDate, parsePatterns));
			title = calendar.get(Calendar.YEAR) + "年"
					+ (calendar.get(Calendar.MONTH) + 1) + "月";
		} catch (Exception e) {
		}
		params.put("title",
				department.name
						+ title
						+ (StringUtils.isEmpty(name) ? StringUtils.EMPTY : "("
								+ name + ")") + "员工刷脸统计表");
		HttpSession session = request.getSession();
		Object user = session.getAttribute("user");
		params.put("name", user == null ? StringUtils.EMPTY : "打印人：" + user);
		params.put("date",
				"打印日期：" + DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
		this.print(request, response, "cardrecord", list, params);
	}

	@RequestMapping("/loadAll")
	public @ResponseBody
	Map<String, Object> loadAll(Long id, String name, String startDate,
			String endDate) {
		Map<String, Object> result = new HashMap<String, Object>();
		if (id == null || id.intValue() == 2 || StringUtils.isEmpty(startDate)
				|| StringUtils.isEmpty(endDate)) {
			result.put("rows", new ArrayList<CardRecord>());
			result.put("total", 0);
			return result;
		}

		Schedule schedule = ScheduleAssembler.convert(scheduleService.get(
				startDate, id));
		if (schedule == null) {
			result.put("rows", new ArrayList<CardRecord>());
			result.put("total", 0);
			return result;
		}
		List<Card> cardList = loadCard(id, name, startDate, endDate, schedule);

		List<Employee> employeeList = loadEmployee(id, name);

		List<CardRecord> list = CardRecordAssembler.convert(employeeList,
				cardList, schedule, endDate);

		result.put("rows", list);
		result.put("total", list.size());
		result.put("schedule", schedule);
		return result;
	}

	private List<Card> loadCard(Long id, String name, String startDate,
			String endDate, Schedule schedule) {
		List<Object> param = new ArrayList<Object>();
		param.add("%@" + id + "@%");

		StringBuilder where = new StringBuilder(
				" employee.department.path like ? and date >= ? and date < ?  ");

		String[] parsePatterns = { "yyyy-MM-dd", "yyyy-M-dd", "yyyy-M-d" };
		Date start = null;
		try {
			start = DateUtils.parseDate(startDate, parsePatterns);
			param.add(new java.sql.Date(start.getTime()));

		} catch (Exception e) {

		}

		Date end = null;
		try {
			end = DateUtils.parseDate(endDate, parsePatterns);
			Calendar calendar = Calendar.getInstance();
			int yyyy = Integer.valueOf(DateFormatUtils.format(end, "yyyy"));
			int mm = Integer.valueOf(DateFormatUtils.format(end, "MM"));
			int dd = Integer.valueOf(DateFormatUtils.format(end, "dd"));

			if (schedule.nightStartTime == null) {
				int h = Integer.valueOf(schedule.afternoonStartTime.substring(
						0, 2));
				int m = Integer.valueOf(schedule.afternoonStartTime.substring(
						2, 4));
				calendar.set(yyyy, mm - 1, dd, h, m, 0);

				calendar.add(Calendar.SECOND, schedule.afternoonEndTime * 60);
				calendar.add(Calendar.SECOND, schedule.afternoonAfterEnd * 60);
			} else {
				int h = Integer
						.valueOf(schedule.nightStartTime.substring(0, 2));
				int m = Integer
						.valueOf(schedule.nightStartTime.substring(2, 4));
				calendar.set(yyyy, mm - 1, dd, h, m, 0);
				calendar.add(Calendar.SECOND, schedule.nightEndTime * 60);
				calendar.add(Calendar.SECOND, schedule.nightAfterEnd * 60);
			}
			param.add(new java.sql.Date(calendar.getTime().getTime()));

		} catch (Exception e) {

		}

		if (StringUtils.isNotEmpty(name)) {
			where.append(" and (employee.name like ? or employee.employeeCode like ? ) ");
			param.add("%" + name + "%");
			param.add("%" + name + "%");
		}

		List<Card> cardList = CardAssembler.convert(cardService
				.loadAll(new PageParam(0, 0, where.toString(), param,
						" date desc ")).rows);
		return cardList;
	}

	private List<Employee> loadEmployee(Long id, String key) {
		List<Object> params = new ArrayList<Object>();

		params.add("%@" + id + "@%");

		if (StringUtils.isNotEmpty(key)) {
			params.add("%" + key + "%");
			params.add("%" + key + "%");
		}

		List<com.card.hwatt.entity.Employee> list = employeeService
				.loadAll(new PageParam(
						0,
						0,
						" department.path like ? "
								+ (StringUtils.isNotEmpty(key) ? " and ( name like ? or employeeCode like ? ) "
										: StringUtils.EMPTY), params,
						" employeeCode asc ")).rows;
		List<Employee> rows = EmployeeAssembler.convert(list);
		return rows;
	}
}
